package com.mediacloud.app.newsmodule.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.viewpager.widget.PagerAdapter;

import com.mediacloud.app.model.activity.BaseBackActivity;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.ShareGridPopUtils;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.newsmodule.view.HackyViewPager;
import com.mediacloud.app.newsmodule.view.PhotoViewAttacher4AppFactory;
import com.mediacloud.app.newsmodule.view.PictureView;
import com.mediacloud.app.newsmodule.view.PictureViewX;

import java.util.ArrayList;
import java.util.List;

public class PhotoNewsImageItemViewActivity extends BaseBackActivity
{


    private static final int UPTATE_INTERVAL_TIME = 10;
    private long lastUpdateTime;

    private SensorManager sensorMag;
    private Sensor gravitySensor;
    float lastX = 0;
    float lastY = 0;
    float lastZ = 0;

    public static void startActivity(Context context, ArticleItem articleItem, CatalogItem catalogItem,String currentImage)
    {
        Intent intent=new Intent(context,PhotoNewsImageItemViewActivity.class);
        intent.putExtra(Intent.ACTION_ATTACH_DATA,articleItem);
        intent.putExtra(Intent.EXTRA_REFERRER,catalogItem);
        intent.putExtra(Intent.ACTION_OPEN_DOCUMENT,currentImage);
        context.startActivity(intent);
    }
    ArticleItem articleItem; CatalogItem catalogItem;String currentImage;
    @Override
    public int getLayoutResID()
    {
        return R.layout.photonews_imageitem_view;
    }


    HackyViewPager viewPager;
    ShareWrap shareWrap;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        viewPager=findViewById(R.id.viewPager);
        viewPager.setBackgroundColor(Color.BLACK);
        articleItem=getIntent().getParcelableExtra(Intent.ACTION_ATTACH_DATA);
        catalogItem=getIntent().getParcelableExtra(Intent.EXTRA_REFERRER);
        currentImage=getIntent().getStringExtra(Intent.ACTION_OPEN_DOCUMENT);
        mTitlebar_MoreContainer.setVisibility(View.VISIBLE);
        List<String>  urls=new ArrayList<>();
        urls.add(currentImage);
        viewPager.setAdapter(new SamplePagerAdapter(urls));
        initGravitySensor();
        shareWrap = new ShareWrap(this,false);
        shareWrap.setShowFunction(true);
        shareWrap.init(articleItem,catalogItem);
    }

    private void initGravitySensor(){

        sensorMag=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
        gravitySensor = sensorMag.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorMag.registerListener(sensorLis, gravitySensor, SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    public void finish()
    {
        sensorMag.unregisterListener(sensorLis);
        super.finish();
    }

    private SensorEventListener sensorLis = new SensorEventListener() {

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
            {
                return;
            }
            long currentUpdateTime = System.currentTimeMillis();
            long timeInterval = currentUpdateTime - lastUpdateTime;
            if (timeInterval < UPTATE_INTERVAL_TIME)
                return;
            lastUpdateTime = currentUpdateTime;
            float x = event.values[SensorManager.DATA_X];
            float y = event.values[SensorManager.DATA_Y];
            float z = event.values[SensorManager.DATA_Z];
            float deltaX = x - lastX;
            float deltaY = y - lastY;
            float deltaZ = z - lastZ;
            //备份本次坐标
            lastX = x;
            lastY = y;
            lastZ = z;
            Log.w("APPTAG", String.format("x:%.2f , deltaX:%.2f ",x,deltaX));

            double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / timeInterval * 10000;
            Log.w("APPTAG", String.format("speed:%.2f",speed));

            if(viewPager.getChildCount()==0||viewPager.getChildAt(0) instanceof PictureView==false)
                return;
            PictureView imageView= (PictureView) viewPager.getChildAt(0);
            Drawable d=imageView.getDrawable();
            if(d==null)
            {
                return;
            }
            final float viewWidth = imageView.getWidth();
            final float viewHeight = imageView.getHeight();
            final int drawableWidth = d.getIntrinsicWidth();
            final int drawableHeight = d.getIntrinsicHeight();
            final float heightScale = viewHeight / drawableHeight;
            final float scale = heightScale;
            final float tx=(viewWidth - drawableWidth * scale) / 2F;
            float percentValue=Math.abs(tx)/SensorManager.GRAVITY_EARTH;
            imageView.mAttacher.onDrag(percentValue*x*-1,0);
        }
    };


    @Override
    protected void moreClicked()
    {
        super.moreClicked();
        shareWrap.show(mRootView);
      //  ShareGridPopUtils.show(this,articleItem,catalogItem,false,false,getWindow().getDecorView());
    }

    private class SamplePagerAdapter extends PagerAdapter
    {
        private List<String> urls;

        public SamplePagerAdapter(List<String> urls)
        {
            this.urls = urls;
        }

        @Override
        public int getCount() {
            if(urls==null)
                return 0;
            return urls.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            if (position >= getCount())
                return null;
            PhotoView pictureViewX = new PhotoView(container.getContext());
            pictureViewX.setId(View.generateViewId());
            pictureViewX.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            pictureViewX.setImageURL(urls.get(position));
            container.addView(pictureViewX, 0);
            return pictureViewX;
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    class PhotoView extends PictureViewX
    {

        public PhotoView(Context context, AttributeSet attr, int defStyle) {
            super(context, attr, defStyle);
        }

        public PhotoView(Context context, AttributeSet attr) {
            super(context, attr);
        }

        public PhotoView(Context context) {
            super(context);
        }

        @Override
        protected void initAttacher() {
            mAttacher=new PhotoViewAttacher4BigImage(this);
        }
    }

    public float currentScale=1;

    class PhotoViewAttacher4BigImage extends PhotoViewAttacher4AppFactory
    {

        public PhotoViewAttacher4BigImage(ImageView imageView) {
            super(imageView);
        }

        @Override
        protected void updateBaseMatrix(Drawable d)
        {
//            super.updateBaseMatrix(d);
            ImageView imageView = getImageView();
            if (null == imageView || null == d) {
                return;
            }
//            zoomTo();
            final float viewWidth = imageView.getWidth();
            final float viewHeight = imageView.getHeight();
            final int drawableWidth = d.getIntrinsicWidth();
            final int drawableHeight = d.getIntrinsicHeight();
            mBaseMatrix.reset();
//            final float widthScale = viewWidth / drawableWidth;
            final float heightScale = viewHeight / drawableHeight;

            final float scale = heightScale;
            currentScale=scale;
            mBaseMatrix.postScale(scale, scale);
            mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
                    (viewHeight - drawableHeight * scale) / 2F);
            resetMatrix();
        }

        @Override
        public boolean onTouch(View v, MotionEvent ev)
        {
            sensorMag.unregisterListener(sensorLis);
            return super.onTouch(v, ev);
        }
    }
}